//
//  SportModel.m
//  GetFit3.0
//
//  Created by zorro on 2017/7/21.
//  Copyright © 2017年 lxc. All rights reserved.
//

#import "SportModel.h"


// http://apidoc.sty028.com/#api-sportsleep-uploadGfUserSport
// PHP http://119.23.8.182:8081/doc/
// http://119.23.8.182:8082/appversion/index

@implementation SportModel

- (instancetype)init {
    self = [super init];
    if (self) {
        _user_id      = SN_USER.user_id;
        _dateString   = [[NSDate date] dateToDayString];
        _step         = 0;
        _distance     = 0;
        _realDistance = 0;
        _calory       = 0;
        NSString *dateY = [[[NSDate date] dateAfterDay:-1] dateToDayString];
        NSString *dateT = [[[NSDate date] dateAfterDay:0] dateToDayString];
        _stepTarget     = SN_USER.target_step;
        _stepquality    = NO;
        _stepBoolFinish = 0;
        
        NSMutableArray *stepArr     = [NSMutableArray array];
        NSMutableArray *distanceArr = [NSMutableArray array];
        NSMutableArray *calArr      = [NSMutableArray array];
        for (int i = 0; i < 48; i++) {
            [stepArr addObject:StrByInt(0)];
            [distanceArr addObject:StrByInt(0)];
            [calArr addObject:StrByInt(0)];
        }
        _stepArray     = [NSArray arrayWithArray:stepArr];
        _distanceArray = [NSArray arrayWithArray:distanceArr];
        _calorArray    = [NSArray arrayWithArray:calArr];
        _stepFinish    = 1;
    }
    
    return self;
}

+ (SportModel *)initWithDate:(NSDate *)date {
    SportModel *model = [[SportModel alloc] init];
    
    model.dateString = [date dateToDayString];
    model.user_id    = SN_USER.user_id;
    model.step       = 0;
    model.distance   = 0;
    model.calory     = 0;
    NSString *dateY = [[[NSDate date] dateAfterDay:-1] dateToDayString];
    NSString *dateT = [[[NSDate date] dateAfterDay:0] dateToDayString];
    model.stepTarget     = SN_USER.target_step;
    model.stepquality    = NO;
    model.stepBoolFinish = 0;
    model.weekCount      = [NSDate getDaysWeekNumberWithSelectDate:date];
    model.monthCount     = [NSDate getDaysMonthNumberWithSelectDate:date];
    model.dayOfWeek      = [NSDate getDaysYearNumberWithSelectDate:date withType:0];
    model.dayOfMonth     = [NSDate getDaysYearNumberWithSelectDate:date withType:1];
    model.yearCount      = [NSDate getDaysYearNumberWithSelectDate:date withType:2];
    
    NSMutableArray *stepArr     = [NSMutableArray array];
    NSMutableArray *distanceArr = [NSMutableArray array];
    NSMutableArray *calArr      = [NSMutableArray array];
    for (int i = 0; i < 48; i++) {
        [stepArr addObject:StrByInt(0)];
        [distanceArr addObject:StrByInt(0)];
        [calArr addObject:StrByInt(0)];
    }
    model.stepArray     = [NSArray arrayWithArray:stepArr];
    model.distanceArray = [NSArray arrayWithArray:distanceArr];
    model.calorArray    = [NSArray arrayWithArray:calArr];
    model.stepFinish    = 1;
    return model;
}

- (void)updateToDBSafely {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, self.dateString];
    SportModel *model = [SportModel searchSingleWithWhere:where orderBy:nil];
    
    if (model) {
        [SportModel updateToDB:self where:nil];
    }
}

+ (SportModel *)getSportModelFromDB {
    SportModel *model = [SportModel getSportModelFromDBWith:[NSDate date]];
    
    return model;
}

+ (SportModel *)getSportModelFromDBWithDayString:(NSString *)string {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, string];
    SportModel *model = [SportModel searchSingleWithWhere:where orderBy:nil];
    
    if (!model) {
        model            = [[SportModel alloc] init];
        model.dateString = string;
        NSDate *ddd = [NSDate dateByString:string];
        model.weekCount  = [NSDate getDaysWeekNumberWithSelectDate:ddd];
        model.monthCount = [NSDate getDaysMonthNumberWithSelectDate:ddd];
        model.dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:ddd withType:0];
        model.dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:ddd withType:1];
        model.yearCount  = [NSDate getDaysYearNumberWithSelectDate:ddd withType:2];
        model.user_id    = SN_USER.user_id;
        model.stepFinish = 1;
        [model updateToDB];
    }
    return model;
}

+ (SportModel *)getSportModelFromDBWith:(NSDate *)date {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and dateString = '%@'",
                       SN_USER.user_id, [date dateToDayString]];
    SportModel *model = [SportModel searchSingleWithWhere:where orderBy:nil];
    
    if (!model) {
        model = [SportModel pedometerSaveEmptyModelToDBWithDate:date isSaveAllDay:NO];
    }
    model.stepFinish = 1;
    return model;
}

+ (SportModel *)pedometerSaveEmptyModelToDBWithDate:(NSDate *)date isSaveAllDay:(BOOL)save {
    SportModel *model = [SportModel initWithDate:date];
    
    [SportModel creatEmptyDataArrayWithModel:model];
    if (![date compareWithDate:[NSDate date]] &&
        [date timeIntervalSince1970] < [[NSDate date] timeIntervalSince1970]) {
        // NSLog(@"model.isSaveAllDay = ..%@", date);
        if (save) {
            model.isSaveAllDay = YES;
        }
    }
    
    [model saveToDB];
    
    return model;
}

// 为模型创建空值的对象
+ (void)creatEmptyDataArrayWithModel:(SportModel *)model {
}

// 表名
+ (NSString *)getTableName {
    return @"SportModel";
}

// 复合主键
+ (NSArray *)getPrimaryKeyUnionArray {
    return @[@"user_id", @"dateString"];
}

// 表版本
+ (int)getTableVersion {
    return 1;
}

+ (void)initialize {
    [super initialize];
    
    [self bindYYJSONKey:@"stepDuration" toProperty:@"stepDuration"];
    [self bindYYJSONKey:@"target_step" toProperty:@"stepTarget"];
    [self bindYYJSONKey:@"data" toProperty:@"detailData"];
    [self bindYYJSONKey:@"date" toProperty:@"dateString"];
    
    [self removePropertyWithColumnName:@"detailData"];
}

- (void)updateRealStepData:(NSData *)data {
    UInt8 val[20] = {0};
    
    [data getBytes:&val length:data.length];
    NSString  *content    = [NSString stringWithFormat:@"%@", data];
    NSInteger tmpStep     = 0;
    NSInteger tmpDistance = 0;
    NSInteger tmpCalory   = 0;
    NSInteger tmpDuration = 0;
    tmpStep     = val[3] * 256 * 256 * 256 + val[4] * 256 * 256 + val[5] * 256 + val[6];
    tmpDistance = val[7] * 256 * 256 * 256 + val[8] * 256 * 256 + val[9] * 256 + val[10];
    tmpCalory   = val[11] * 256 * 256 * 256 + val[12] * 256 * 256 + val[13] * 256 + val[14];
    tmpDuration = val[15] * 256 + val[16];
    
    SportModel *model = SN_PublicClass.todaySport;
    model.step = tmpStep;
    if (SN_USER.isMetricSystem) {
        model.distance = tmpDistance * 1.609344;
    } else {
        model.distance = tmpDistance;
    }
    model.realDistance = tmpDistance;
    
    model.calory       = tmpCalory;
    model.stepDuration = tmpDuration;
    
    if (model.step > model.stepTarget) {
        model.stepquality    = YES;
        model.stepBoolFinish = 1;
    } else {
        model.stepquality    = NO;
        model.stepBoolFinish = 0;
    }
    LogWrite(@"实时运动", content, nil);
    
    NSInteger      currentMinIndex = [NSDate getCurrentMinTotal]/30;
    NSInteger      lastStep        = 0;
    NSMutableArray *newStepArray   = [[NSMutableArray alloc] init];
    for (NSString *step in model.stepArray) {
        lastStep += step.integerValue;
        [newStepArray addObject:step];
    }
    
    NSString  *lastIndexStep = [model.stepArray objectAtIndex:currentMinIndex];
    NSInteger replaceStep    = 0;
    if (model.step > lastStep) {
        replaceStep = lastIndexStep.integerValue + model.step - lastStep;
        [newStepArray replaceObjectAtIndex:currentMinIndex withObject:StrByInt(replaceStep)];
        model.stepArray = [NSArray arrayWithArray:newStepArray];
    }
    
    NSLog(@"实时步数 当前时间下标>>>%d  最后的总步数>>>%d 实时步数%d 误差步数>>>%d", currentMinIndex, lastStep, model.step, model.step - lastStep);
    [model updateToDB];
    //        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //            [model updateToDB];
    //            NSLog(@"实时步数>>>>>>>>>%d", model.step);
    //            // 回到主线程
    //            dispatch_async(dispatch_get_main_queue(), ^{
    //            });
    //        });
}

// 步数大数据
+ (void)updateSportData:(NSData *)sportData {
    UInt8 val[20] = {0};
    
    [sportData getBytes:&val length:sportData.length];
    NSString *content = [NSString stringWithFormat:@"%@", sportData];
    // 开始
    if (val[3] == 0 || val[3] == 6) {
        [SN_PublicClass.stepArray removeAllObjects];
        SN_PublicClass.sportTotal = 0;
        for (int i = 0; i < 48; i++) {
            [SN_PublicClass.stepArray addObject:@"0"];
        }
    }
    //防止手环过来的数据漏发val[3] == 0或val[3] == 6这条导致数组为空
    if (SN_PublicClass.stepArray.count==0) {
        for (int i = 0; i < 48; i++) {
            [SN_PublicClass.stepArray addObject:@"0"];
        }
    }
    if (val[2] == 3) {
        if (val[3] == 0) {
            LogWrite(@"今日步数大数据", content, nil);
        } else if (val[3] == 6) {
            LogWrite(@"昨日步数大数据", content, nil);
        } else {
            LogWrite(nil, content, nil);
        }
    } else if (val[2] == 5) {
        if (val[3] == 0) {
            LogWrite(@"今日距离大数据", content, nil);
        } else if (val[3] == 6) {
            LogWrite(@"昨日距离大数据", content, nil);
        } else {
            LogWrite(nil, content, nil);
        }
    } else {
        if (val[3] == 0) {
            LogWrite(@"今日卡路里大数据", content, nil);
        } else if (val[3] == 6) {
            LogWrite(@"昨日卡路里大数据", content, nil);
        } else {
            LogWrite(nil, content, nil);
        }
    }
    for (int i = 4; i < 19; i += 2) {
        if (val[3] >= 0 && val[3] <= 11) {
            NSInteger number   = val[i] * 256 + val[i + 1];
            int       indexRow = val[3];
            if (val[3] > 5) {
                indexRow = val[3] - 6;
            }
            int index = indexRow * 8 + (i - 4)/2;
            [SN_PublicClass.stepArray replaceObjectAtIndex:index withObject:StrByInt(number)];
            SN_PublicClass.sportTotal += number;
        }
    }
    SportModel *model;
    if (val[3] == 5) {
        model = SN_PublicClass.todaySport;
        [model updateSportDataWithType:val[2] with:YES];
        [model updateToDB];
    } else if (val[3] == 11) {
        model = SN_PublicClass.yesSport;
        [model updateSportDataWithType:val[2] with:NO];
        [model updateToDB];
        //        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //            [model updateToDB];
        //        });
    }
}

// 分类型保存
- (void)updateSportDataWithType:(NSInteger)type with:(BOOL)today {
    if (type == 3) { // 计步
        _step = SN_PublicClass.sportTotal;
        NSLog(@"大数据步数.>>>>%d", _step);
        _stepArray = [NSArray arrayWithArray:SN_PublicClass.stepArray];
        if (_step >= _stepTarget) {//测试
            _stepquality    = YES;
            _stepBoolFinish = 1;
        } else {
            _stepquality    = NO;
            _stepBoolFinish = 0;
        }
    } else if (type == 5) { // 距离
        if (!today) {
            if (SN_USER.isMetricSystem) {
                _distance = SN_PublicClass.sportTotal *1.609344;
            } else {
                _distance = SN_PublicClass.sportTotal;
            }
            _realDistance = SN_PublicClass.sportTotal;
        }
        _distanceArray = [NSArray arrayWithArray:SN_PublicClass.stepArray];
    } else if (type == 6) { // 卡路里
        if (!today) {
            _calory = SN_PublicClass.sportTotal;
            //            if (_calory > 10000) {
            //                int cal = 1.0 *_distance *SN_USER.weight *1.036 / 1000;
            //                _calory = cal;
            //            }
        }
        _calorArray = [NSArray arrayWithArray:SN_PublicClass.stepArray];
    }
}

+ (void)getMaxDayStep {
    NSString *where   = [NSString stringWithFormat:@"select max(step) from SportModel where user_id = '%@' ", SN_USER.user_id];
    NSString *maxStep = [[self getUsingLKDBHelper] executeScalarWithSQL:where arguments:nil];
    
    SN_USER.max_step = maxStep.integerValue;
    NSString *dateWhere   = [NSString stringWithFormat:@"select dateString from SportModel where step = '%@' and user_id = '%@'", maxStep, SN_USER.user_id];
    NSString *maxStepDate = [[self getUsingLKDBHelper] executeScalarWithSQL:dateWhere arguments:nil];
    SN_USER.max_step_date = [maxStepDate stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
}

+ (void)getmaxContinueDays {
    NSString       *where    = [NSString stringWithFormat:@"user_id = '%@'", SN_USER.user_id];
    NSMutableArray *totalArr = [SportModel searchWithWhere:where];
    NSMutableArray *reachArr = [NSMutableArray array];
    
    for (SportModel *model in totalArr) {
        if (model.stepquality && model.stepTarget > 0) {
            [reachArr addObject:model];
        }
    }
    NSMutableArray *continueArr = [NSMutableArray array];
    NSMutableArray *subArr      = [NSMutableArray array];
    SportModel     *tmpModel    = [[SportModel alloc]init];
    for (int i = 0; i < reachArr.count; i++) {
        SportModel *model = reachArr[i];
        if (i == 0) {
            [subArr addObject:model];
            tmpModel = model;
            if (reachArr.count == 1) {
                [continueArr addObject:subArr];
            }
        } else {
            NSDate           *date1     = [NSDate dateByString:tmpModel.dateString];
            NSDate           *date2     = [NSDate dateByString:model.dateString];
            NSCalendar       *gregorian = [NSCalendar currentCalendar];
            unsigned int     unitFlags  = NSCalendarUnitDay;
            NSDateComponents *comps     = [gregorian components:unitFlags fromDate:date1 toDate:date2 options:0];
            if (comps.day == 1) {
                [subArr addObject:model];
                if (i==reachArr.count-1) {
                    [continueArr addObject:subArr];
                }
            } else {
                [continueArr addObject:subArr];
                subArr = [NSMutableArray array];
                [subArr addObject:model];
            }
            tmpModel = model;
        }
    }
    NSArray *result = [continueArr sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        NSMutableArray *arr1 = obj1;
        NSMutableArray *arr2 = obj2;
        return [@(arr1.count) compare:@(arr2.count)];
    }];
    NSArray *maxReachArr = result.lastObject;
    maxReachArr = [maxReachArr sortedArrayUsingComparator:^NSComparisonResult (id _Nonnull obj1, id _Nonnull obj2) {
        SportModel *model1 = obj1;
        SportModel *model2 = obj2;
        return [[NSDate dateByString:model1.dateString] compare:[NSDate dateByString:model2.dateString]];
    }];
    SN_USER.max_reach_times = maxReachArr.count;
    SN_USER.max_reach_start = [((SportModel *)maxReachArr.firstObject).dateString stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
    SN_USER.max_reach_end   = [((SportModel *)maxReachArr.lastObject).dateString stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
}

+ (void)getMaxWeekStep {
    NSDate    *startDate = [[NSDate date] beginningOfWeek];
    NSDate    *endDate   = [[NSDate date] endOfWeek];
    NSInteger maxStep    = 0;
    NSInteger tmpStep    = 0;
    
    for (int i = 0; i < MAXFLOAT; i++) {
        if (i>0) {
            startDate = [startDate dateByAddingWeeks:-1];
            endDate   = [endDate dateByAddingWeeks:-1];
        }
        if ([startDate compare:SN_USER.registerDate] == -1) {
            return;
        } else {
            NSString       *where = [NSString stringWithFormat:@"user_id = '%@' and dateString >= '%@' and dateString <= '%@'", SN_USER.user_id, startDate.dateToDayString, endDate.dateToDayString];
            NSMutableArray *arr   = [SportModel searchColumn:@"step" where:where orderBy:@"dateString" offset:0 count:7];
            tmpStep = [[arr valueForKeyPath:@"@sum.floatValue"] integerValue];
            if (tmpStep > maxStep) {
                maxStep                = tmpStep;
                SN_USER.max_week_step  = maxStep;
                SN_USER.max_week_start = [startDate.dateToDayString stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
                SN_USER.max_week_end   = [endDate.dateToDayString stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
            }
        }
    }
}

+ (void)getMaxMonthStep {
    NSDate    *startDate = [[NSDate date] beginningOfMonth];
    NSDate    *endDate   = [[NSDate date] endOfMonth];
    NSInteger maxStep    = 0;
    NSInteger tmpStep    = 0;
    
    for (int i = 0; i < MAXFLOAT; i++) {
        if (i>0) {
            startDate = [startDate dateByAddingMonths:-1];
            endDate   = [startDate endOfMonth];
        }
        if ([startDate compare:SN_USER.registerDate] == -1) {
            return;
        } else {
            NSString       *where = [NSString stringWithFormat:@"user_id = '%@' and dateString >= '%@' and dateString <= '%@'", SN_USER.user_id, startDate.dateToDayString, endDate.dateToDayString];
            NSMutableArray *arr   = [SportModel searchColumn:@"step" where:where orderBy:@"dateString" offset:0 count:31];
            tmpStep = [[arr valueForKeyPath:@"@sum.floatValue"] integerValue];
            if (tmpStep > maxStep) {
                maxStep                = tmpStep;
                SN_USER.max_month_step = maxStep;
                SN_USER.max_month      = [[startDate.dateToDayString substringToIndex:7] stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
            }
        }
    }
}

+ (void)sportTransEnd {
    NSLog(@"运动数据同步完成>>>");
    
    [SN_Net updateEveryModelWithType:HJUpdateStep];
}

+ (NSInteger)localSportDays {
    NSString *where = [NSString stringWithFormat:@"user_id = '%@' and step > 0", SN_USER.user_id];
    
    return [SportModel rowCountWithWhere:where];
}

// 将数据从服务器同步下来
- (void)saveToDBByDownload {
    NSDate *date = [NSDate dateByString:self.dateString];
    
    self.weekCount  = [NSDate getDaysWeekNumberWithSelectDate:date];
    self.monthCount = [NSDate getDaysMonthNumberWithSelectDate:date];
    self.dayOfWeek  = [NSDate getDaysYearNumberWithSelectDate:date withType:0];
    self.dayOfMonth = [NSDate getDaysYearNumberWithSelectDate:date withType:1];
    self.yearCount  = [NSDate getDaysYearNumberWithSelectDate:date withType:2];
    
    NSDictionary *dict = (NSDictionary *)[self.detailData parseJSONString];
    if ([dict isKindOfClass:NSDictionary.class] && dict.allKeys.count > 0) {
        self.stepArray     = [NSArray arrayWithArray:dict[@"step"]];
        self.distanceArray = [NSArray arrayWithArray:dict[@"distance"]];
        self.calorArray    = [NSArray arrayWithArray:dict[@"cal"]];
    }
    
    if (self.stepTarget > 0 && self.stepTarget > 0 && self.step >= self.stepTarget) {
        self.stepquality = YES;
    }
    
    NSString *todayStr = [[NSDate date] dateToDayString];
    if (self.dateString != todayStr) {
        self.isSaveAllDay   = YES;
        self.stepFinish     = YES;
        self.stepBoolFinish = YES;
    }
    [self updateToDB];
}

@end

